package com.donger.business.upms.controller;


import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.donger.auth.component.UserDetail;
import com.donger.auth.utils.SecurityUtils;
import com.donger.business.upms.entity.SysPermission;
import com.donger.business.upms.service.ISysPermissionService;
import com.donger.common.core.exception.BizException;
import com.donger.common.core.utils.Res;
import com.donger.common.core.utils.Result;
import com.donger.common.log.annotation.AutoLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜单管理 前端控制器
 * </p>
 *
 * @author 7326
 */
@AllArgsConstructor
@RestController
@RequestMapping("/sys/permission")
@Slf4j
@Api(tags = "权限开放API")
public class SysPermissionController {

    private static final String MODULE_NAME = "系统权限管理";

    private final ISysPermissionService sysPermissionService;





    @GetMapping("/nav")
    public Result nav(String code){

        UserDetail user = SecurityUtils.getUser();
        List<SysPermission> userMenuNoButton = sysPermissionService.getUserMenuNoButton(user.getUserId(),code);
        return Res.ok(userMenuNoButton);
    }


    /**
     * 所有权限列表
     */
    @GetMapping("/select")
    @ApiOperation(value = "菜单选择-多顶级节点")
    @AutoLog(moduleName = MODULE_NAME)
    public Result<List<SysPermission>> select() {
        // 获取当前用户的角色
        UserDetail user = SecurityUtils.getUser();
        List<SysPermission> permissionList = sysPermissionService.getUserMenuList(user.getId());
        SysPermission root = new SysPermission();
        root.setId(0L);
        root.setTitle("顶级菜单");
        root.setChildren(permissionList);
        List<SysPermission> roots = new ArrayList<>();
        roots.add(root);

        return Res.ok(roots);
    }


    /**
     * 所有权限列表
     */
    @GetMapping("/tree")
    @ApiOperation(value = "菜单列表")
    @AutoLog(moduleName = MODULE_NAME)
    public Result<List<SysPermission>> list() {
        // 获取当前用户的角色
        UserDetail user = SecurityUtils.getUser();
        List<SysPermission> permissionList = sysPermissionService.getUserMenuList(user.getId());
        return Res.ok(permissionList);
    }


    /**
     * 菜单信息
     */
    @GetMapping("/info/{menuId}")
    @ApiOperation(value = "权限详情")
    public Result<SysPermission> info(@ApiParam(value = "权限ID") @PathVariable("menuId") Long menuId) {
        return Res.ok(sysPermissionService.getById(menuId));
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @PreAuthorize("@pms.hasPermission('sys:permission:add')")
    @ApiOperation(value = "新增权限,具备权限:sys:permission:add")
    public Result<Boolean> save(@RequestBody @Valid SysPermission menu) {
        if (menu.getParentId() == null) {
            menu.setParentId(0L);
        }
        return Res.ok(sysPermissionService.save(menu));
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @PreAuthorize("@pms.hasPermission('sys:permission:update')")
    @ApiOperation(value = "更新权限,具备权限:sys:permission:update")
    public Result<Boolean> update(@RequestBody SysPermission menu) {
        //数据校验
        verifyForm(menu);
        return Res.ok(sysPermissionService.updateById(menu));
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{menuId}")
    @ApiOperation("根据权限ID删除权限,具备权限:sys:permission:delete")
    @PreAuthorize("@pms.hasPermission('sys:permission:delete')")
    public Result<Boolean> delete(@PathVariable("menuId") Long menuId) {
        //判断是否有子菜单或按钮
        int count = sysPermissionService.count(Wrappers.<SysPermission>lambdaQuery().eq(SysPermission::getParentId, menuId));
        if (count > 0) {
            return Res.error("请先删除子菜单或按钮");
        }
        sysPermissionService.removeById(menuId);
        return Res.ok();
    }

    /**
     * 验证参数是否正确
     */
    private void verifyForm(SysPermission menu) {
        if (StrUtil.isBlank(menu.getTitle())) {
            throw new BizException("菜单名称不能为空");
        }

        if (menu.getParentId() == null) {
            throw new BizException("上级菜单不能为空");
        }

    }
}

